using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;

namespace EBookReader.Library.Data
{
    [Serializable]
    public class PageInfo
    {
        [NonSerialized]
        private string url;
        [NonSerialized]
        private string host;
        [NonSerialized]
        private int port;
        [NonSerialized]
        private string buffer;
        [NonSerialized]
        private int length;
        [NonSerialized]
        private int received;

        public PageInfo()
        {
            url = string.Empty;
            host = string.Empty;
            buffer = string.Empty;
            length = -1;
            received = -1;
            port = 80;
        }

        public string Url
        {
            get { return url; }
            set { url = value; }
        }

        public string Host
        {
            get { return host; }
            set { host = value; }
        }

        public int Port
        {
            get { return port; }
            set { port = value; }
        }

        public string Buffer
        {
            get { return buffer; }
            set { buffer = value; }
        }

        public int Length
        {
            get { return length; }
            set { length = value; }
        }

        public int Recevied
        {
            get { return received; }
            set { received = value; }
        }

        public static PageInfo Parse(string url)
        {
            if(string.IsNullOrEmpty(url))
            {
                throw new Exception("url is null.");
            }
            PageInfo info=new PageInfo();
            url = url.ToLower().Trim();
            url = url.Replace('\\', '/');
            if (url.StartsWith("http://"))
                url = url.Substring(7);
            if (Regex.IsMatch(url, "(.*?)\\s*(.*)"))
            {
                Match match = Regex.Match(url, "(.*?)\\s*(\\/.*)");
                info.Host = match.Groups[1].Value;
                info.Port = 80;
                info.Url = match.Groups[2].Value;
            }
            else if (Regex.IsMatch(url, "(.*?):(\\d+)\\s+(\\/.*)"))
            {
                Match match = Regex.Match(url, "(.*?):(\\d+)\\s+(\\/.*)");
                info.Host = match.Groups[1].Value;
                info.Port = Convert.ToInt32(match.Groups[2].Value);
                info.Url = match.Groups[3].Value;
            }
            return info;
        }
    }
}
